const handler = async (request) => {
  const html = `<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IP 地址信息查询</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f6f9;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            color: #333;
            flex-direction: column;
        }

       .container {
            background-color: #fff;
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 800px;
            text-align: left;
            margin-bottom: 20px;
            transition: box-shadow 0.3s ease-in-out;
        }

       .container:hover {
            box-shadow: 0 12px 36px rgba(0, 0, 0, 0.2);
        }

        h1 {
            margin-bottom: 20px;
            font-size: 2.1rem;
            color: #2c3e50;
            letter-spacing: 1px;
            text-align: center;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        h2 {
            margin-bottom: 20px;
            font-size: 1.3rem;
            color: #2c3e50;
            letter-spacing: 1px;
            text-align: center;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        input[type="text"] {
            width: 100%;
            padding: 15px;
            margin-bottom: 20px;
            border: 2px solid #dfe4ea;
            border-radius: 10px;
            font-size: 1.2rem;
            transition: border-color 0.3s ease-in-out;
        }

        input[type="text"]:focus {
            outline: none;
            border-color: #3498db;
        }

        button {
            width: 100%;
            padding: 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1.2rem;
            cursor: pointer;
            transition: background-color 0.3s ease-in-out;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        button:hover {
            background-color: #2980b9;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
        }

        ul {
            list-style-type: none;
            padding: 0;
            margin: 20px 0;
            border-top: 1px solid #dfe4ea;
            border-bottom: 1px solid #dfe4ea;
        }

        li {
            margin: 15px 0;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #dfe4ea;
        }

        li:last-child {
            border-bottom: none;
        }

       .loading {
            margin-top: 20px;
            font-size: 1.2rem;
            color: #95a5a6;
            animation: fadeInOut 1s infinite alternate;
        }

       .copy-btn {
            flex: 1;
            background-color: #ecf0f1;
            border: none;
            color: #34495e;
            padding: 4px 8px;
            margin-left: 10px;
            border-radius: 6px;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s ease-in-out;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            white-space: nowrap;
        }

       .copy-btn:hover {
            background-color: #bdc3c7;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
        }

       .info-item span {
            flex: 4;
            white-space: nowrap;
        }

       .google-accessible {
            color: green;
            font-weight: bold;
        }

       .google-restricted {
            color: red;
            font-weight: bold;
        }

        @keyframes fadeInOut {
            from {
                opacity: 0.5;
            }

            to {
                opacity: 1;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>IP 地址查询</h1>
        <input type="text" id="ipInput" placeholder="请输入IP地址" />
        <button onclick="queryIP()">查询</button>
        <div id="result"></div>
        <div id="loading" class="loading" style="display: none;">正在查询中...</div>
    </div>

    <div class="container">
        <h2>检测能否访问Google服务</h2>
        <div id="ipInfo" class="loading">正在加载您的IP信息...</div>
    </div>

    <script>
        async function queryIP() {
            const resultDiv = document.getElementById('result');
            const loadingDiv = document.getElementById('loading');
            const ipInput = document.getElementById('ipInput').value.trim();
            loadingDiv.style.display = 'block';
            resultDiv.innerHTML = '';

            try {
                const url = ipInput ? \`https://ipchaxun.onrender.com/ip/\${encodeURIComponent(ipInput)}\` : 'https://ipchaxun.onrender.com/ip';
                const headers = {
                    'Authorization': 'Bearer Snail'
                };
                const response = await fetch(url, { headers });
                if (!response.ok) throw new Error('网络响应失败');

                const data = await response.json();
                if (data.code !== 0) {
                    throw new Error(data.message || '查询失败');
                }

                const info = data.data;
                const address = [info.country, info.province, info.city].filter(Boolean).join(' ');
                const ipAddr = ipInput || info.ip;
                const infoList = [
                    { label: 'IP 地址:', value: ipAddr },
                    { label: '国家:', value: info.country || '未知' },
                    { label: '地址:', value: address },
                    { label: '运营商:', value: info.as || '未知' },
                    { label: '经纬度:', value: \`\${info.latitude || '未知'}, \${info.longitude || '未知'}\` }
                ];

                resultDiv.innerHTML = \`<ul>\${infoList.map(item =>
                    item.label === 'IP 地址:' ? 
                        \`<li class="info-item"><span>\${item.label} \${item.value}</span><button class="copy-btn" onclick="copyText('\${item.value}')">复制IP</button></li>\` :
                        \`<li>\${item.label} \${item.value}</li>\`
                ).join('')}</ul>\`;
            } catch (error) {
                resultDiv.innerHTML = \`<p style="color: red;">\${error.message}</p>\`;
            } finally {
                loadingDiv.style.display = 'none';
            }
        }

        function copyText(text) {
            navigator.clipboard.writeText(text).then(() => {
                alert('ip地址已经复制');
            }).catch(err => {
                console.error('无法复制文本: ', err);
            });
        }

        async function fetchIPInfo() {
            const ipInfoDiv = document.getElementById('ipInfo');
            try {
                const response = await fetch('https://api.vore.top/api/IPdata?ip=');
                if (!response.ok) throw new Error('网络请求失败');

                const data = await response.json();
                const isCnIp = data.ipinfo?.cnip;
                const region = data.ipdata?.info1 || '';
                const city = data.ipdata?.info2 || '未知';
                const isp = data.ipdata?.isp || '未知';

                if (isCnIp && !['香港', '澳门', '台湾'].includes(region)) {
                    ipInfoDiv.innerHTML = \`
                        <ul>
                            <li class="google-restricted">您的IP为中国大陆，无法访问Google服务。</li>
                        </ul>
                    \`;
                } else {
                    const ip = data.ipinfo?.text || '未知';
                    const infoList = [
                        { label: 'IP 地址', value: ip },
                        { label: '国家/地区', value: region },
                        { label: '城市', value: city },
                        { label: '运营商', value: isp }
                    ];
                    ipInfoDiv.innerHTML = \`
                        <ul>
                            \${infoList.map(item => \`<li><strong>\${item.label}:</strong> \${item.value}</li>\`).join('')}
                            <li class="google-accessible">您的IP非中国大陆，可以访问Google服务。</li>
                        </ul>
                    \`;
                }
            } catch (error) {
                ipInfoDiv.textContent = \`加载失败: \${error.message}\`;
            }
        }

        window.onload = () => {
            queryIP();
            fetchIPInfo();
        };
    </script>
</body>

</html>`;

  return new Response(html, {
    headers: {
      'Content-Type': 'text/html;charset=UTF-8'
    }
  });
};

addEventListener('fetch', (event) => {
  event.respondWith(handler(event.request));
});
